﻿using Pulog.Models;
using System.Linq;
using System.Collections.Generic;

namespace Pulog.Models
{
    public partial class SettingRepository : ISettingRepository
    {
        private PulogDataContext dc = new PulogDataContext();
       
        public List<Setting> GetSettings()
        {
            return dc.Settings.ToList();
        }

        public void SaveSettings(List<Setting> settings)
        {
            dc.Settings.InsertAllOnSubmit(settings);
        }

        public string GetSettingByKey(string key)
        {
            return dc.Settings.Single(s => s.Key == key).Value;
        }

        public void Save()
        {
            dc.SubmitChanges();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <returns>
        /// 0 -- succeed
        /// 1 -- oldpassword does not match
        /// </returns>
        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            var user = dc.Users.Single(s => s.userName == userName);
            if (user.password.ToUpper() == Helper.GetMD5Hash(oldPassword))
            {
                user.password = Helper.GetMD5Hash(newPassword);
                Save();
                return true;
            }
            else
            {
                return false;
            }
        }

    }
}